class New < ActiveRecord::Base
	has_many :categories_news, :class_name => "CategoriesNew"
	has_many :categories, :through => :categories_news

  before_destroy :delete_images

  def delete_images
    ResourceImage.delete_all(:belong_type => Iyaoi::ImageType::NEWS, :belong_id => self.id) 
  end

	def clear_up_categories
		self.categories = []
		save!
	end

  def images
    ResourceImage.find(:all, :conditions => ["belong_id=? AND belong_type=?", self.id, Iyaoi::ImageType::NEWS])
  end

	def categories_ids
		categories.collect{|e| e.id }
	end

	def add_categories(category_ids)
		category_ids.each do |id|
			self.categories << Category.find_by_id(id)
		end
	end
  
  def add_images(image_ids)
		return if image_ids.nil? or image_ids.size == 0
    old_image_ids = images.collect{|e| e.id }
    ResourceImage.delete_all(["id IN (?)", old_image_ids - image_ids])
    image_ids.each do |id|
      image = ResourceImage.find_by_id(id)
      next unless image
      image.belong_type = Iyaoi::ImageType::NEWS
      image.belong_id   = self.id
      image.save!
    end
  end
end
